<template>
  <el-drawer :title="drawerProps.title" v-model="drawerVisible" size="60%" :before-close="handleClose" :destroy-on-close="true">
    <el-form
      ref="ruleFormRef"
      :model="drawerProps.row"
      :rules="rules"
      label-width="120px"
      label-suffix=" :"
      :disabled="drawerProps.isView"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="迭代名称" prop="name">
            <el-input v-model="drawerProps.row!.name" placeholder="请输入迭代名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="迭代核心价值" prop="key_value">
            <el-input
              v-model="drawerProps.row!.key_value"
              placeholder="请输入迭代核心价值"
              type="textarea"
              :rows="3"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迭代SM" prop="sm">
            <user-select placeholder="请选择用户" v-model="drawerProps.row!.sm"></user-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迭代PO" prop="po">
            <user-select placeholder="请选择用户" v-model="drawerProps.row!.po"></user-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属产品" prop="productIds">
            <product-select placeholder="请选择产品" :multiple="true" v-model="drawerProps.row!.productIds"></product-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迭代团队" prop="teamId">
            <cascader-select
              data-key="orgs"
              :request-api="() => apiService.findTree('orgs', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
              :config="{ label: 'name', value: '_id', checkStrictly: true }"
              v-model:item-value="drawerProps.row!.teamId"
            ></cascader-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迭代版本" prop="version">
            <el-input v-model="drawerProps.row!.version" placeholder="请输入迭代版本" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="drawerProps.row!.startDate"
              type="date"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="drawerProps.row!.endDate"
              type="date"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="研发天数" prop="devDays">
            <el-input-number
              v-model="drawerProps.row!.devDays"
              :min="0"
              controls-position="right"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迭代状态" prop="state">
            <common-select
              data-key="SPRINT_STATE"
              placeholder="请选择迭代状态"
              :request-api="() => apiService.findClassify('SPRINT_STATE')"
              v-model="drawerProps.row!.state"
            ></common-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 投入用户资源 -->
      <group-title title="投入资源"></group-title>
      <el-table :data="sprintUsers" border style="width: 100%; margin-bottom: 20px">
        <el-table-column prop="userId" label="用户">
          <template #default="scope">
            <user-select placeholder="请选择用户" v-model="scope.row.userId"></user-select>
          </template>
        </el-table-column>
        <el-table-column prop="orgId" label="组织" width="280">
          <template #default="scope">
            <cascader-select
              data-key="orgs"
              :request-api="() => apiService.findTree('orgs', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
              :config="{ label: 'name', value: '_id', checkStrictly: true }"
              v-model:item-value="scope.row!.orgId"
            ></cascader-select>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="用户类型">
          <template #default="scope">
            <el-select v-model="scope.row.type" placeholder="请选择用户类型" clearable>
              <el-option label="前端" value="0"></el-option>
              <el-option label="后端" value="1"></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="coefficient" label="投入系数">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.coefficient"
              :min="0"
              :max="1"
              :step="0.1"
              controls-position="right"
              style="width: 100%"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="devDays" label="工作天数">
          <template #default="scope">
            <el-input-number v-model="scope.row.devDays" :min="0" controls-position="right" style="width: 100%"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" link @click="removeSprintUser(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" link @click="addSprintUser">+ 添加投入用户</el-button>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button v-if="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="SprintDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import apiService from "@/api/services/apiService";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import CascaderSelect from "@/components/SelectFilter/cascader-select.vue";
import productSelect from "@/components/SelectFilter/product-select.vue";
import userSelect from "@/components/SelectFilter/user-select.vue";
import groupTitle from "@/components/application/form/group-title.vue";
import { Sprint } from "./types/sprint";

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<Sprint.Sprint>;
  api?: (tableName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 冲刺投入用户资源
const sprintUsers = ref<Sprint.SprintUser[]>([]);

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入迭代名称", trigger: "blur" }],
  sm: [{ required: true, message: "请选择迭代SM", trigger: "change" }],
  po: [{ required: true, message: "请选择迭代PO", trigger: "change" }],
  startDate: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  state: [{ required: true, message: "请选择迭代状态", trigger: "change" }]
});

// 表单实例
const ruleFormRef = ref<FormInstance>();

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;

  // 初始化冲刺投入用户资源
  sprintUsers.value = [];
  if (params.row._id) {
    const res = await apiService.find<Sprint.SprintUser[]>("sprint_user", { sprintId: params.row._id });
    sprintUsers.value = res.data.map(user => ({
      ...user,
      coefficient: user.coefficient || 1,
      devDays: user.devDays || 0
    }));
  }

  // 如果没有投入用户，添加一个空的
  if (sprintUsers.value.length === 0) {
    addSprintUser();
  }
};

// 添加投入用户
const addSprintUser = () => {
  sprintUsers.value.push({
    sprintId: drawerProps.value.row._id || "",
    userId: "",
    type: "0",
    orgId: "",
    coefficient: 1,
    devDays: 0,
    note: ""
  });
};

// 删除投入用户
const removeSprintUser = (index: number) => {
  sprintUsers.value.splice(index, 1);
};

// 提交数据（新增/编辑）
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;

    try {
      // 处理主表数据
      const rowData = { ...drawerProps.value.row };

      // 如果是编辑，需要保留_id
      if (drawerProps.value.title === "编辑" && rowData._id) {
        // 更新主表
        await apiService.updateById(drawerProps.value.tbName, { _id: rowData._id, ...rowData });
      } else {
        // 新增主表
        const res = await apiService.save(drawerProps.value.tbName, rowData);
        // 设置sprintId用于子表
        rowData._id = (res as any).data._id;
      }

      // 处理子表数据（投入用户资源）
      // 先删除原有的投入用户资源
      if (rowData._id) {
        await apiService.deleteByCondition("sprint_user", { sprintId: rowData._id });
      }

      // 添加新的投入用户资源
      if (sprintUsers.value.length > 0 && rowData._id) {
        const sprintUserList = sprintUsers.value.map(user => ({
          ...user,
          sprintId: rowData._id
        }));
        console.log(sprintUserList);
        await apiService.saveList("sprint_user", sprintUserList);
      }

      ElMessage.success(`${drawerProps.value.title}成功`);
      drawerVisible.value = false;
      drawerProps.value.getTableList && drawerProps.value.getTableList();
    } catch (error) {
      console.error(`${drawerProps.value.title}失败:`, error);
      ElMessage.error(`${drawerProps.value.title}失败`);
    }
  });
};

// 关闭抽屉
const handleClose = () => {
  ruleFormRef.value!.resetFields();
  drawerVisible.value = false;
};

// 暴露方法
defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  padding: 16px 20px;
  margin-bottom: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}
:deep(.el-drawer__body) {
  padding: 20px;
  overflow-y: auto;
}
</style>
